layui.use(['table', 'admin', 'ax', 'func', 'form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var func = layui.func;

    /**
     * 首页轮播图管理
     */
    var HomePage = {
        tableId: "homePageTable"
    };

    /**
     * 初始化表格的列
     */
    HomePage.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {type: 'numbers', title: '序号', width: 80},
            {field: 'id', hide: true, title: ''},
            {field: 'title', sort: true, title: '标题', width: 160},
            {field: 'linkUrl', sort: true, title: '跳转路径', width: 160},
            {field: 'imageUrl', sort: true, title: '图片路径', templet: '#imgTmp', width: 160},
            {field: 'type', sort: true, title: '操作类型', templet: formatType, width: 160},
            {field: 'status', sort: true, title: '状态', templet: HomePage.formatStatus}, //2.禁用,1.启用
            {field: 'createTime', sort: true, title: '创建时间', width: 180},
            // {field: 'createUser', sort: true, title: '创建人'},
            // {field: 'updateUser', sort: true, title: '修改人'},
            {field: 'updateTime', sort: true, title: '修改时间', width: 180},
            // {field: 'deleteFlag', sort: true, title: '0.正常,1.删除'},
            {align: 'center', toolbar: '#tableBar', title: '操作', width: 160}
        ]];
    };

    //加载状态
    HomePage.loadAllStatusInfo = function () {
        $.ajax({
            url: Changein.ctxPath + "/homePage/loadAllStatusInfo",
            type: "GET",
            dataType: "json",
            success: function (result) {
                if (result && result.code == 200) {
                    let list = result.data;
                    for (let type in list) {
                        let strContent = "";
                        let objList = list[type];
                        for (let i in objList) {
                            let valContent = objList[i];
                            strContent += "<option value='" + i + "'>" + valContent + "</option>";
                        }
                        let appendObj = $("select[name=\'" + type + "\']");
                        appendObj.append(strContent);
                    }
                    form.render('select');
                }
            }
        });
    };
    HomePage.loadAllStatusInfo();

    function formatType(d) {
        if (null == d.type) return "";
        var typeText = $("select[name='type'] option[value='" + d.type + "']").text();
        return typeText;
    }

    /**
     * 点击查询按钮
     */
    HomePage.search = function () {
        var queryData = getParam();

        table.reload(HomePage.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 获取查询参数
     */
    function getParam() {
        var queryData = {};
        queryData['type'] = $("select[name='type'] option:checked").val();
        return queryData;
    }

    /**
     * 弹出添加对话框
     */
    HomePage.openAddDlg = function () {
        func.open({
            title: '添加首页轮播图',
            content: Changein.ctxPath + '/homePage/add',
            maxmin: true,
            tableId: HomePage.tableId
        });
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    HomePage.openEditDlg = function (data) {
        func.open({
            title: '修改首页轮播图',
            content: Changein.ctxPath + '/homePage/edit?id=' + data.id,
            tableId: HomePage.tableId
        });
    };


    HomePage.formatStatus = function formatStatus(d) {
        //状态
        if (!d.status) return "";
        let checkedStatus = d.status == 1 ? 'checked' : '';
        return "<input type='checkbox'  " + checkedStatus + " value='" + d.status + "' lay-skin='switch' lay-text='启用|禁用' lay-filter='statusOptFilter' successId='" + d.id + "'>";
    }

    /**
     * 删除
     */
    var deleteBatchLock = false;
    HomePage.deleteBatch = function () {
        if (!deleteBatchLock) {
            var checkRows = table.checkStatus(HomePage.tableId);
            if (checkRows.data.length == 0) {
                Changein.error("请选择要删除的数据");
                return false;
            }
            var arr = [];
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit != 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                Changein.error("选中数据全部已审核，请选择未审核的数据");
                return false;
            }
            var operation = function () {
                deleteBatchLock = true;
                var ajax = new $ax(Changein.ctxPath + "/homePage/batchDeleteByIds", function (data) {
                    if (data.code != 200) {
                        Changein.error("删除失败！" + data.message);
                    } else {
                        Changein.success("删除成功！");
                    }
                    deleteBatchLock = false;
                    table.reload(HomePage.tableId);
                }, function (data) {
                    deleteBatchLock = false;
                    Changein.error("删除失败！" + data.responseJSON.message)
                });
                ajax.set({"ids": arr.toString()});
                ajax.start();
            }
            Changein.confirm("是否删除?", operation);
        } else {
            Changein.error("正在删除中");
        }
    };

    /**
     * 审核
     */
    var auditLock = false;
    HomePage.auditBatch = function () {
        if (!auditLock) {
            var arr = [];
            var checkRows = table.checkStatus(HomePage.tableId);
            if (checkRows.data.length == 0) {
                Changein.error("请选择要审核的数据");
                return false;
            }
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit != 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                Changein.error("选中数据全部已审核");
                return false;
            }
            var operation = function () {
                auditLock = true;
                var ajax = new $ax(Changein.ctxPath + "/homePage/setAudit", function (data) {
                    if (data.code != 200) {
                        Changein.error("审核失败！" + data.message);
                    } else {
                        Changein.success("审核成功！");
                    }
                    auditLock = false;
                    table.reload(HomePage.tableId);
                }, function (data) {
                    auditLock = false;
                    Changein.error("审核失败！" + data.responseJSON.message)
                });
                ajax.set({"id": arr.toString()});
                ajax.start();
            }
            Changein.confirm("是否审核?", operation);
        } else {
            Changein.error("正在审核中");
        }
    };

    /**
     * 反审核
     */
    var unAuditLock = false;
    HomePage.unAuditBatch = function () {
        if (!unAuditLock) {
            var arr = [];
            var checkRows = table.checkStatus(HomePage.tableId);
            if (checkRows.data.length == 0) {
                Changein.error("请选择要反审核的数据");
                return false;
            }
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit == 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                Changein.error("选中数据全部未审核");
                return false;
            }
            var operation = function () {
                unAuditLock = true;
                var ajax = new $ax(Changein.ctxPath + "/homePage/setUnAudit", function (data) {
                    if (data.code != 200) {
                        Changein.error("反审核失败！" + data.message);
                    } else {
                        Changein.success("反审核成功！");
                    }
                    unAuditLock = false;
                    table.reload(HomePage.tableId);
                }, function (data) {
                    unAuditLock = false;
                    Changein.error("反审核失败！" + data.responseJSON.message)
                });
                ajax.set({"id": arr.toString()});
                ajax.start();
            }
            Changein.confirm("是否反审核?", operation);
        } else {
            Changein.error("正在反审核中");
        }
    };


    /**
     * 导出excel按钮,EXPORT_CODE需要在开发设置-导出设置里配置
     */
    HomePage.exportExcel = function () {
        Changein.exportData(tableResult.config.id, "EXPORT_CODE", table, getParam());
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    HomePage.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Changein.ctxPath + "/homePage/delete", function (data) {
                Changein.success("删除成功!");
                table.reload(HomePage.tableId);
            }, function (data) {
                Changein.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Changein.confirm("是否删除?", operation);
    };
    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    var deleteLock = false;
    HomePage.onDeleteItem = function (data) {
        if (data.audit == 1) {
            Changein.error("选中数据已审核，请选择未审核的数据");
            return false;
        }
        var operation = function () {
            deleteLock = true;
            var ajax = new $ax(Changein.ctxPath + "/homePage/delete", function (data) {
                deleteLock = false;
                if (data.code != 200) {
                    Changein.error("删除失败！" + data.message);
                } else {
                    Changein.success("删除成功！");
                }
                table.reload(HomePage.tableId);
            }, function (data) {
                deleteLock = false;
                Changein.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        if (!deleteLock) {
            Changein.confirm("是否删除?", operation);
        } else {
            Changein.error("正在删除中");
        }
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + HomePage.tableId,
        url: Changein.ctxPath + '/homePage/list',
        page: true,
        height: "full-130",
        cellMinWidth: 100,
        limits: [20, 30, 50, 100],
        limit: 20,
        cols: HomePage.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        HomePage.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        HomePage.openAddDlg();
    });
    // 删除
    $("#btnDel").click(function () {
        HomePage.deleteBatch();
    });

    //审核
    $('#btnAudit').click(function () {
        HomePage.auditBatch();
    });

    //反审核
    $('#btnUnAudit').click(function () {
        HomePage.unAuditBatch();
    });
    // 导出excel
    $('#btnExp').click(function () {
        var checkRows = table.checkStatus(HomePage.tableId);
        if (checkRows.data.length === 0) {
            HomePage.exportExcel();
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }

    });
    //下载模板,TEMPLATE_CODE需要在开发设置-模板管理里配置
    $("#btnDownloadTemplate").click(function () {
        Changein.downLoadTempate("TEMPLATE_CODE");
    });
    // 工具条点击事件
    table.on('tool(' + HomePage.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            HomePage.openEditDlg(data);
        } else if (layEvent === 'delete') {
            HomePage.onDeleteItem(data);
        }
    });

    layui.use('layer', function () {
        let layer = layui.layer;
        $("body").on("click", '.layui-img', function () {
            var src = this.src;
            if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0 || !src) {
                layer.alert("图片不存在");
                return false;
            }
            var width = this.naturalWidth;
            var height = this.naturalHeight;
            if (height > 400) {
                height = 400;
            }
            if (width > 800) {
                width = 800;
            }
            layer.open({
                type: 1
                , shadeClose: true
                , closeBtn: 0
                , scrollbar: false
                , title: false //不显示标题栏
                , area: [width + 'px', height + 'px']
                , shade: 0.3
                , id: 'LAY_layuipro' //设定一个id，防止重复弹出
                , content: "<img src='" + src + "' style='width:" + width + "px;height:" + height + "px'/>"
            });
        });
    });

    form.on("switch(statusOptFilter)", function (data) {
        let id = $(data.elem).attr("successId");
        let statusFlag = 2;
        if (data.elem.checked) {
            statusFlag = 1;
        }
        let param = {id: id, status: statusFlag};
        $.ajax({
            url: Changein.ctxPath + '/homePage/editItem?',
            data: param,
            type: "POST",
            success: function (result) {
                if (result && result.code == 200) {
                    if (data.elem.checked) {
                        Changein.success("启用成功！");
                    } else {
                        Changein.success("禁用成功！");
                    }
                } else {
                    Changein.error("操作失败！");
                }
            }, dataType: "json"
        });
    })
});
